<template>
  <div ref="chartContainer" style="width: 100%; height: 500px;"></div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue';
import * as echarts from 'echarts';
import 'echarts/lib/chart/candlestick';
import 'echarts/lib/component/title';
import 'echarts/lib/component/tooltip';
import 'echarts/lib/component/toolbox';
import 'echarts/lib/component/legend';

const props = defineProps({
  data: {
    type: Array,
    required: true
  }
});

const chartContainer = ref(null);
let chartInstance = null;

const initChart = () => {
  chartInstance = echarts.init(chartContainer.value);
  updateChart(props.data);
};

const updateChart = (data) => {
  if (!chartInstance) return;

  const option = {
    title: {
      text: data.length > 0 ? data[data.length-1].stockCode + "_" + data[0].stockName + "_" + data[data.length-1].tradeMoney + "_" + data[data.length-1].date + "_涨跌:" + data[data.length-1].changePercent : "k线图",
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    xAxis: {
      type: 'category',
      data: data.map(item => item.date),
      scale: true,
      boundaryGap: false
    },
    yAxis: {
      scale: true,
      splitLine: {
        show: false
      }
    },
    series: [
      {
        name: data.length > 0 ? 'K线' + data[data.length-1].tradeMoney : "k线",
        type: 'candlestick',
        data: data.map(item => [item.open, item.close, item.low, item.high]),
        itemStyle: {
          color: 'white',
          color0: '#12af52',
          borderColor: '#f6524c',
          borderColor0: '#12af52'
        }
      }
    ]
  };

  chartInstance.setOption(option, true);
};

onMounted(() => {
  initChart();
});

watch(() => props.data, (newData) => {
  updateChart(newData);
}, { deep: true });

</script>

<style scoped>
/* 可选：自定义样式 */
</style>
